#!/bin/bash
#chkconfig: 345 20 80
# description: agentservice daemon
# processname: agentservice
# agentservice daemon

runtime=<%=@installdir%>
configfile=${runtime}/agentservice.cfg	
USER=<%=@wasuser%>

function stopAgentServerDaemons {
	while read line; do
		current_process=$(ps -ef |grep $line |grep -v grep | awk '{print $2}')
		if [ "$current_process" != "" ]; then
			echo "...stopping processes for $line"
			kill -TERM $current_process
		else
			echo "...agent service daemon $line not running"
		fi
	done < $configfile
}

function startAgentServerDaemons {
	while read line; do
		echo "...starting agent $line"
		su - ${USER} -c "nohup ${runtime}/bin/agentserver.sh $line >${runtime}/logs/${line}.log 2>${runtime}/logs/${line}_error.log &" 
	done < $configfile
}

function statusAgentServerDaemons {
	while read line; do
		current_process=$(ps -ef |grep $line |grep -v grep | awk '{print $2}')
		if [ "$current_process" != "" ]; then
			echo "...agent service daemon $line: [RUNNING]"
		else
			echo "...agent service daemon $line: [STOPPED]"
		fi
	done < $configfile
	
}

function usage {
	echo "Usage $0 {status|start|stop|restart}"
}

case "$1" in 
	start) 
		startAgentServerDaemons 
		statusAgentServerDaemons
	;;
	status) 
		statusAgentServerDaemons
	;;
	stop)
		stopAgentServerDaemons
		statusAgentServerDaemons
	;;
	restart)
		stopAgentServerDaemons
		startAgentServerDaemons
		statusAgentServerDaemons
	;;
	*)
		usage
	;;
esac



